#include "Utils.h"

bool compareUInt(int left, int right) {
	return left < right;
}

CaseData* processInput(_TCHAR* path) {

	ifstream file;
	CaseData* result = new CaseData;
	tstring sPath = path;
	int idealSpectrumSize;

	file.open(sPath);
	if(file.is_open()) {
		unsigned int dotPos = sPath.find((_TCHAR*)".");
		if(dotPos == string::npos) {
			cout << "Wrong file name.";
			return NULL;
		}

		unsigned int signPos = sPath.find((_TCHAR*)"+");
		if(signPos != string::npos) {
			result->errorType = ERR_TYPE_POS;
		} else {
			signPos = sPath.find((_TCHAR*)"-");
			if(signPos != string::npos) {
				result->errorType = ERR_TYPE_NEG;
			} else {		
				cout << "Wrong file name.";
				return NULL;
			}
		}

#ifdef _UNICODE
		idealSpectrumSize = _wtoi(sPath.substr(dotPos + 1, signPos - dotPos).c_str());
		result->errorNum = _wtoi(sPath.substr(signPos + 1).c_str());
#else
		idealSpectrumSize = atoi(sPath.substr(dotPos + 1, signPos - dotPos).c_str());
		result->errorNum = atoi(sPath.substr(signPos + 1).c_str());
#endif
		if(result->errorType == ERR_TYPE_NEG)
			result->spectrumSize = idealSpectrumSize - result->errorNum;
		else			
			result->spectrumSize = idealSpectrumSize + result->errorNum;

		result->olignucs = new unsigned int[result->spectrumSize];

		string line;
		int index = 0;
		while (index != result->spectrumSize)
		{
			getline(file, line);
			result->olignucs[index++] = str2Nuc(line);
		}

		/*vector<unsigned int> temp(result->olignucs, result->olignucs + olignucsCount);
		delete[] result->olignucs;
		result -> olignucs = new unsigned int[olignucsCount];
		sort(temp.begin(), temp.end());
		copy(temp.begin(), temp.end(), result->olignucs);
		temp.clear();*/

		//cout << "Line: " << line << " == " << result->olignucs[index - 1] << ", index: " << index << endl;
		result->olignucLength = line.length();
		result->chainLength = idealSpectrumSize + result->olignucLength - 1;

		file.close();
	} else {
		cout << "Cannot open file." << endl;
		return NULL;
	}

	return result;	
}

unsigned int str2Nuc(string input) {
	unsigned int nucleotide = 0;
	int index = 0;
	while(index < (int)input.length()) {		
		nucleotide <<= 2;
		switch(input[index++]) {
		case 'A':
			nucleotide |= A;
			break;
		case 'C':
			nucleotide |= C;
			break;
		case 'G':
			nucleotide |= G;
			break;
		case 'T':
			nucleotide |= T;
			break;
		default:
			cout << "Cos nie gra." << endl;
		}
	}
	return nucleotide;
}

string nuc2Str(unsigned int olignuc, int nucCount) {
	int mask = 3u;
	char* temp = new char[nucCount + 1];
	temp[nucCount] = '\0';
	while(nucCount--) {
		switch(olignuc & mask) {
		case A:
			temp[nucCount] = 'A';
			break;
		case C:
			temp[nucCount] = 'C';
			break;
		case G:
			temp[nucCount] = 'G';
			break;
		case T:
			temp[nucCount] = 'T';
			break;
		}
		olignuc >>= 2;
	}
	return string(temp);
}